package com.cxyd.modules.wms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cxyd.common.page.PageData;
import com.cxyd.common.exception.RootException;
import com.cxyd.common.service.impl.CrudServiceImpl;
import com.cxyd.modules.sys.dto.SysUserDTO;
import com.cxyd.modules.sys.service.SysUserService;
import com.cxyd.modules.wms.dao.*;
import com.cxyd.modules.wms.dto.ContainerDTO;
import com.cxyd.modules.wms.entity.*;
import com.cxyd.modules.wms.service.ContainerService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;
import java.util.Map;

/**
 * 容器信息
 *
 * @author g_Cycle gengruyi01@163.com
 * @since 1.0.0 2023-04-27
 */
@Service
public class ContainerServiceImpl extends CrudServiceImpl<ContainerDao, ContainerEntity, ContainerDTO> implements ContainerService {
    private final SysUserService userService;
    private final ContainerDao containerDao;
    private final StockDao stockDao;
    private final TaskDao taskDao;
    private final ContainerDetailDao containerDetailDao;
    private final LocateDao locateDao;

    public ContainerServiceImpl(SysUserService userService, ContainerDao containerDao, StockDao stockDao, TaskDao taskDao, ContainerDetailDao containerDetailDao, LocateDao locateDao) {
        this.userService = userService;
        this.containerDao = containerDao;
        this.stockDao = stockDao;
        this.taskDao = taskDao;
        this.containerDetailDao = containerDetailDao;
        this.locateDao = locateDao;
    }

    @Override
    public PageData<ContainerDTO> page(Map<String, Object> params) {
        //1.查询容器信息
        final IPage<ContainerEntity> page = baseDao.selectPage(
                getPage(params, "cont_id", true),
                getWrapper(params)
        );
        //2.获取用户信息
        final List<SysUserDTO> userList = userService.getList();
        //3.将creator与updater的username通过id进行绑定
        page.getRecords().forEach(entity -> {
            if (entity.getCreator() != null) {
                entity.setCreatorName(userService.getUsernameById(entity.getCreator(), userList));
            }
            if (entity.getUpdater() != null) {
                entity.setUpdaterName(userService.getUsernameById(entity.getUpdater(), userList));
            }
//
            if(entity.getContType().equals("2")||entity.getContType().equals("3"))
            {
                Long countStock = stockDao.selectCount(new QueryWrapper<StockEntity>()
                        .eq("cont_no",entity.getContNo()));
                Long countDetail = containerDetailDao.selectCount(new QueryWrapper<ContainerDetailEntity>()
                        .eq("cont_no",entity.getContNo()));
                if(countStock == 0 || countDetail == 0)
                {
                    entity.setUseRate(0);
                }
                else
                {
                    double result = (double) countStock/countDetail;
                    entity.setUseRate(result*100);

                }

            }
            else
            {
                //算體積
                try {
                    double stockVo = stockDao.getStockVo(entity.getContNo()).doubleValue();


                    String[] numbers = entity.getContDescription().split("\\*");
                    double result = 1;

                    for (String number : numbers) {
                        result *= Double.parseDouble(number);
                    }
                    double contVo = result;
                    entity.setUseRate(stockVo/contVo*100);
                }
                catch (Exception ex)
                {
                    entity.setUseRate(0);

                }


            }
        });
        return getPageData(page, ContainerDTO.class);
    }

    @Override
    public QueryWrapper<ContainerEntity> getWrapper(Map<String, Object> params) {
        String contNo = (String) params.get("contNo");
        String contType = (String) params.get("contType");

        QueryWrapper<ContainerEntity> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(contNo), "cont_no", contNo);
        wrapper.eq(StringUtils.isNotBlank(contType), "cont_type", contType);

        return wrapper;
    }
    @Override
    public void delete(@RequestBody Long[] ids) {

       for (int i = 0; i < ids.length; i++) {
           deleteContById(ids[i]);
       }
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteContById(Long id) {
        String contNo = baseDao.selectById(id).getContNo();

        //存在库存不允许删
        if (stockDao.exists(new QueryWrapper<StockEntity>()
                .eq("cont_no",contNo))) {
            throw new RootException("料箱【"+contNo+"】有库存，不能删除！");
        }

        //存在移动任务不允许删
        if (taskDao.exists(new QueryWrapper<TaskEntity>()
                .eq("cont_no",contNo)
                .lt("task_st",2))) {
            throw new RootException("料箱【"+contNo+"】有设备任务，不能删除！");
        }

        //在库位上也不能删除
        if (locateDao.exists(new QueryWrapper<LocateEntity>()
                .eq("cont_no",contNo))) {
            throw new RootException("料箱【"+contNo+"】在库位上，不能直接删除！");
        }

        containerDetailDao.deleteByContId(id);
        baseDao.deleteById(id);
    }

}